package com.yk.airline.component.crawler.impl;

import com.yk.airline.component.crawler.api.ICrawlerService;
import com.yk.airline.dao.origindata.api.IOriginDataDao;
import com.yk.airline.model.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.*;

/**
 * Project Name:airlinecrawler
 * File Name:CrawlerServiceImpl
 * Package Name:com.yk.airline.component.crawler.impl
 * Date:2018/1/30 14:56
 * Author:zhangshaoyang
 * Description:
 * Copyright (c) 2018, 重庆云凯科技有限公司 All Rights Reserved.
 */
@Service("crawlerService")
public class CrawlerServiceImpl implements ICrawlerService {

    @Resource(name = "originDataDao")
    private IOriginDataDao originDataDao;


    /**
     * 抓取网页
     *
     * @param webDriver
     * @param captureMarkModel
     * @param airLineModel
     * @param captureWebsiteModel
     * @param time
     * @return
     * @throws InterruptedException
     */
    @Override
    public Object crawlerHtmlByWebdriver(FirefoxDriver webDriver, CaptureMarkModel captureMarkModel, AirLineModel airLineModel, CaptureWebsiteModel captureWebsiteModel, String time)
            throws InterruptedException {
        try {
            if (captureWebsiteModel.getName().equals("携程")) {
                try {
                    String xiechengUrl = captureWebsiteModel.getUrl() + airLineModel.getCityByOriginPlace().getAbbreviate() +
                            "-" + airLineModel.getCityByArrivePlace().getAbbreviate() + "-day-1.html?DDate1=" + time;
                    webDriver.get(xiechengUrl);
//                    Thread.sleep(5000);
                    new WebDriverWait(webDriver, 30).until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(".search_box.search_box_tag.search_box_light")));
                    List<WebElement> search_box = webDriver.findElementsByCssSelector(".search_box.search_box_tag.search_box_light");
                    for (WebElement element : search_box) {
                        if (!element.findElements(By.cssSelector(".J_expandBtn.btn_book.arrow_down")).isEmpty()) {
                            WebElement arrow_down = element.findElement(By.cssSelector(".J_expandBtn.btn_book.arrow_down"));
                            webDriver.executeScript("arguments[0].scrollIntoView(false)", arrow_down);
                            element.findElement(By.cssSelector(".J_expandBtn.btn_book.arrow_down")).click();
                            element.findElements(By.className("arrow_down")).forEach(WebElement::click);
                            webDriver.executeScript("window.scrollTo(0,document.body.scrollHeight)");
                            Thread.sleep(500);
                        } else {
                            webDriver.findElement(By.id("btnReSearch")).click();
                        }
                    }
                    Document html = Jsoup.parse(webDriver.getPageSource());
                    saveModel(captureMarkModel, airLineModel, captureWebsiteModel, String.valueOf(html));
                } catch (Exception e) {
                    e.printStackTrace();
                    this.crawlerHtmlByWebdriver(webDriver, captureMarkModel, airLineModel, captureWebsiteModel, time);
                }
            }
            if (captureWebsiteModel.getName().equals("同程")) {
                try {
                    webDriver.get(captureWebsiteModel.getUrl());
                    new WebDriverWait(webDriver, 30).until(ExpectedConditions.presenceOfElementLocated(By.id("airplaneRadio1")));
                    //行程类型
                    WebElement tripType = webDriver.findElement(By.id("airplaneRadio1"));
                    if (!tripType.isSelected()) {
                        tripType.click();
                    }
                    //出发城市
                    WebElement depCity = webDriver.findElement(By.id("txtAirplaneCity1"));
                    //到达城市
                    WebElement arrCity = webDriver.findElement(By.id("txtAirplaneCity2"));
                    //出发时间
                    WebElement depTime = webDriver.findElement(By.id("txtAirplaneTime1"));
                    //搜索
                    WebElement searchButton = webDriver.findElement(By.id("airplaneSubmit"));
                    depCity.clear();
                    String originPlace = airLineModel.getCityByOriginPlace().getName();
                    String arrivePlace = airLineModel.getCityByArrivePlace().getName();
                    depCity.sendKeys(originPlace);
                    System.out.println("出发城市：" + originPlace);
                    arrCity.clear();
                    arrCity.sendKeys(arrivePlace);
                    System.out.println("到达城市：" + arrivePlace);
                    depTime.clear();
                    depTime.sendKeys(time);
                    System.out.println("出发时间：" + time);
                    webDriver.executeScript("$(arguments[0]).click()", searchButton);
                    new WebDriverWait(webDriver, 30).until(ExpectedConditions.presenceOfElementLocated(By.className("flist_box")));
                    List<WebElement> flist_box = webDriver.findElementsByClassName("flist_box");
                    for (WebElement element : flist_box) {
                        element.findElement(By.className("link_orderB")).click();
//                        element.findElements(By.className("other_more")).forEach(WebElement::click);
                    }
                    Document html = Jsoup.parse(webDriver.getPageSource());
                    saveModel(captureMarkModel, airLineModel, captureWebsiteModel, String.valueOf(html));
                } catch (Exception e) {
                    e.printStackTrace();
                    this.crawlerHtmlByWebdriver(webDriver, captureMarkModel, airLineModel, captureWebsiteModel, time);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            webDriver.close();
        }
        return null;
    }

    /**
     * 保存model
     *
     * @param airLineModel
     * @param captureWebsiteModel
     * @param html
     * @return
     */
    @Override
    public Object saveModel(CaptureMarkModel captureMarkModel, AirLineModel airLineModel, CaptureWebsiteModel
            captureWebsiteModel, String html) {

        OriginDataModel model = new OriginDataModel();
        model.setHtml(String.valueOf(html));
        model.setAirLineByAirLine(airLineModel);
        model.setCaptureWebsiteByCaptureUrl(captureWebsiteModel);
        model.setCaptureMarkByCaptureMarkId(captureMarkModel);
        model.setCreateTime(new Timestamp(System.currentTimeMillis()));
        model.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        this.originDataDao.save(model);
        return null;
    }

    /**
     * 判断元素是否存在
     *
     * @param webDriver
     * @param elementName
     * @return
     */
    boolean ElementExist(WebDriver webDriver, By elementName) {
        try {
            webDriver.findElement(elementName);
            return true;
        } catch (org.openqa.selenium.NoSuchElementException ex) {
            return false;
        }
    }

}
